/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package klasy;

import baza.DBManager;
import java.io.IOException;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;

/**
 *
 * @author Cyga
 */
public class OpisBean {

    private Opis opis = new Opis();
    private List<Opis> lista;

    public List<Opis> getLista() {

        EntityManager em = DBManager.getManager().createEntityManager();
        List list = em.createNamedQuery("Opis.findAll").getResultList();
        em.close();
        return list;
    }

    public void setLista(List<Opis> lista) {
        this.lista = lista;
    }

    public OpisBean() {
    }

    public void setOpis(Opis opis) {
        this.opis = opis;
    }

    public Opis getOpis() {
        return opis;
    }

    public String dodaj() throws IOException {

        EntityManager em = DBManager.getManager().createEntityManager();
        em.getTransaction().begin();

        em.persist(opis);
        this.dodajInformacje("dodano rekord nr.: " + opis.getOpisId());
        em.getTransaction().commit();
        this.opis = new Opis();
        em.close();

        return null;
    }

    public String usun() {
        int ktory;
        EntityManager em = DBManager.getManager().createEntityManager();
        em.getTransaction().begin();
        this.opis = em.find(Opis.class, opis.getOpisId());
        ktory = opis.getOpisId();
        em.remove(this.opis);
        this.opis = new Opis();
        em.getTransaction().commit();
        this.dodajInformacje("usunieto rekord nr.: " + ktory);
        em.close();

        return null;
    }

    public void opisListener() {

        String ids = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("opis_id").toString();
        int id = Integer.parseInt(ids);
        this.opis.setOpisId(id);

    }

    public void dodajInformacje(String s) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, s, ""));
    }
}
